import { Ref } from "vue";
import { usePureForm, UseFormOptions } from "./useForm";

import usePage, { UsePageOptions } from "./usePage";
import { omit, pick } from "lodash-es";

const formOptionKeys = [
  "depsKeys",
  "submitAfterReset",
  "autoSubmit",
  "defaultModel",
] as const;

interface UseTableOptions<TSearch extends object>
  extends UsePageOptions<TSearch, any>,
    Pick<UseFormOptions<TSearch>, (typeof formOptionKeys)[number]> {
  // 开启路由
  routerQuery?: boolean;
}

const useTable = <TData = any, TSearch extends object = Record<string, any>>(
  url: string | Ref<string>,
  options: UseTableOptions<TSearch> = {}
) => {
  const { model, refForm, ...formResult } = usePureForm<TSearch>(
    () => {
      pagination.page = 1;
      execute();
    },
    {
      submitAfterReset: true,
      ...pick(options, formOptionKeys),
      defaultModel: options.defaultSearch,
    }
  );

  const { pagination, onFetchResponse, execute, ...rest } = usePage<
    TData,
    TSearch
  >(url, {
    ...omit(options, formOptionKeys),
    defaultSearch: model as any,
  });

  // 直接再执行一次，参数与上一次一样
  const refresh = () => execute();

  const bindNodeForPlus = (e?: any) => {
    if (e?.form) {
      refForm.value = e.form;
    }
  };

  return {
    refForm,
    pagination,
    search: model,
    execute,
    refresh,
    onFetchResponse,
    bindNodeForPlus,

    ...formResult,
    ...rest,
  };
};

export default useTable;
